<template>
    <div style="padding:30px;">
        <el-alert :closable="false" title="">
            <transition name="fade-transform" mode="out-in">
                <template>
                    <div>
                        <upload-excel-component v-if="isShow" :on-success="handleSuccess"
                            :before-upload="beforeUpload" />
                        <EditButton @add="onAdd" @refresh="onRefresh" :listData="getList" :filterFieldName="getFields"
                            @search="onSearch"></EditButton>
                        <el-table v-loading="listLoading" :height="iHeight" :data="list" style="width: 100%">
                            <!-- <el-table-column prop="deptId" label="ID">
                            </el-table-column> -->
                            <el-table-column prop="deptName" label="科室名称">
                            </el-table-column>
                            <el-table-column prop="deptCode" label="科室编号">
                            </el-table-column>
                            <el-table-column prop="deptType" label="科室类型">
                            </el-table-column>
                            <el-table-column prop="location" label="科室位置">
                            </el-table-column>
                            <el-table-column prop="status" label="科室状态">
                            </el-table-column>
                            <el-table-column fixed="right" label="操作" width="150">
                                <template slot-scope="scope">
                                    <EditTableButton @click-button="handleClick" :data="scope.row"></EditTableButton>
                                </template>
                            </el-table-column>
                        </el-table>
                        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                            :current-page="currentPage" :page-sizes="[10, 20, 30, 40, 50, 100]" :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper" :total="totalSize">
                        </el-pagination>
                        <edit-multiplay-form @sendUpdate="update" ref="editForm"></edit-multiplay-form>
                    </div>
                </template>
            </transition>
        </el-alert>
    </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { DeptsModule } from '@/store/modules/dept'
import { FormDataUtils, IFormCommonMultData, TouchType } from '@/views/common/data/ICommon';
import EditTableButton from "@/views/common/edit-table-button.vue"
import EditButton from "@/views/common/edit-button.vue"
import { IDeptModel } from '@/api/types';
import EditMultiplayForm from '@/views/common/edit-multiplay-form.vue';
import { RoomsModule } from '@/store/modules/room';
import UploadExcelComponent from '@/components/UploadExcel/index.vue'


@Component({
    name: 'Dept',
    components: {
        UploadExcelComponent,
        EditTableButton,
        EditButton,
        EditMultiplayForm
    }
})
export default class extends Vue {
    public allList: Array<IDeptModel> = []
    public list: Array<IDeptModel> = []
    public listLoading: boolean = false
    scope: any;
    $refs: any;
    public optType: string = ""
    public isShow = false;
    public iHeight = window.innerHeight - 300;
    public currentPage: number = 1;
    public pageSize: number = 10;
    public totalSize: number = 0;
    public setShowList() {
        let startIndex = this.pageSize * (this.currentPage - 1);
        this.list = this.allList.filter((value, index) => {
            return index >= startIndex && index < startIndex + this.pageSize;
        });
    }

    created() {
        this.init()
    }
    public getList() {
        return this.allList;
    }
    public getFields() {
        return "deptName"
    }

    //操作相关处理
    public async handleClick(type: TouchType, row: any) {
        if (type === TouchType.DELETE) {
            DeptsModule.deleteDepts(row.deptId).then(v => {
                if (v) {
                    this.list = this.list.filter(value => {
                        return value.deptId != row.deptId
                    })
                }
            });
            return;
        }
        this.optType = type;
        if (type === TouchType.SEE || type === TouchType.EDIT) {
            let keys = Object.keys(row)
            let data: Array<IFormCommonMultData> = await FormDataUtils.getFormsMultiplay(row, "depts", (key: string) => {
                return this.$t(key);
            }, type === TouchType.SEE ? keys : ['deptId'], ["rooms", "updateTime"], [{
                filed: "roomIds", key: "roomId", value: "roomName", isMultiplay: true, getSelectFunc: async () => {
                    return RoomsModule.getRooms()
                }
            }])
            console.error("数据:", data)
            this.$refs.editForm.showForm(data, type === TouchType.EDIT)
        } else if (type === TouchType.ADD) {
            let mod: IDeptModel = {
                deptCode: "",
                deptId: "",
                deptName: "",
                deptType: "",
                isLast: "",
                location: "",
                parentCode: "",
                roomIds: "",
                status: "",
            }
            let data = FormDataUtils.getForms(mod, "depts", (key: string) => {
                return this.$t(key);
            }, [], ["rooms", "roomIds", "status", "updateTime"])
            this.$refs.editForm.showForm(data, true)
        }
    }

    //更新成功
    public update(obj: any) {
        console.error(obj, this.optType);

        if (this.optType === TouchType.ADD) {
            DeptsModule.insertDepts(obj).then(v => {
                console.error(v)
                if (v === 1) {//成功了
                    this.list.push(obj);
                }
            }).catch(ex => {
                console.error(ex);
            })
            return;
        }
        DeptsModule.updateDepts(obj).then(v => {
            console.error(v)
            if (v === 1) {//成功了
                for (let i = 0; i < this.list.length; i++) {
                    if (this.list[i].deptId === obj.deptId) {
                        this.list[i].deptName = obj.deptName;
                        this.list[i].deptCode = obj.deptCode;
                        this.list[i].deptType = obj.deptType;
                        this.list[i].isLast = obj.isLast;
                        this.list[i].location = obj.location;
                        this.list[i].parentCode = obj.parentCode;
                        this.list[i].status = obj.status;
                        break;
                    }
                }
            } else if (!obj.deptId && v) {
                obj.deptId = v;
                this.list.push(obj);
            }
        }).catch(ex => {
            console.error(ex);
        })
    }

    public onAdd() {
        this.handleClick(TouchType.ADD, null);
    }

    public onRefresh() {
        console.error("onClick onRefresh");
        this.isShow = true;
    }

    public onSearch(val: any) {
        this.list = val
    }


    public async init() {
        this.list = [];
        this.listLoading = true
        let result: any = await DeptsModule.getDepts();//.getDeviceColors()
        this.list = result
        this.allList = result
        this.totalSize = this.allList.length;
        this.setShowList();
        setTimeout(() => {
            this.listLoading = false
        }, 0.5 * 1000)
    }

    public handleSizeChange(val: number) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val;
        this.setShowList();
    }
    public handleCurrentChange(val: number) {
        console.log(`当前页: ${val}`);
        this.currentPage = val;
        this.setShowList();
    }


    public beforeUpload(file: File) {
        const isLt5M = file.size / 1024 / 1024 < 5
        if (isLt5M) {
            return true
        }
        this.$message({
            message: 'Please do not upload files larger than 1m in size.',
            type: 'warning'
        })
        return false
    }

    public async handleSuccess({ results, header }: { results: any, header: string[] }) {
        let arr: Array<IDeptModel> = [];
        for (let i = 0; i < results.length; i++) {
            let mod: IDeptModel = {
                deptId: results[i].depId,
                deptCode: results[i].depCode,
                deptName: results[i].depName,
                deptType: results[i].depType,
                isLast: results[i].isLast,
                status: results[i].status,
                parentCode: results[i].parentCode,
                location: results[i].location
            }
            arr.push(mod)
        }
        console.error("数据:", arr);
        await DeptsModule.batchSaveDepts(arr);
    }
}
</script>